<!--新增订单--选择商品-->
<template>

    <div class="select-goods-root">
        <el-dialog
                title="选择订单商品"
                :visible.sync="dialogVisible"
                :close-on-click-modal="false"
                width="68%"
                :close="closeNull"
                :before-close="closeNull">
            <el-form ref="form" :model="form" label-width="80px">
                <el-form-item label="商品名称">
                    <!-- <el-input v-model="form.goodsName" clearable style="width: 70%" @keyup.enter.native="getGoodsDetailByGoodsName"></el-input> -->
                    <el-button type="primary" icon="el-icon-search" size="small" @click="getGoodsDetailByGoodsName" style="margin-left: 3px; margin-right: 3px;"></el-button>

                    <el-select
                        v-model="form.goodsName"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请输入商品名称"
                        @change="getGoodsDetailByGoodsName"
                        :remote-method="getGoodsList"
                        :loading="loading">
                        <el-option
                            v-for="item in options"
                            :key="item.goodsCode"
                            :label="item.label"
                            :value="item.label">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品编号">
                    <el-input v-model="form.goodsCode" clearable @input="getGoodsDetailByGoodsCode"></el-input>
                </el-form-item>

                <div v-if="tableData.row && tableData.row.length > 0">
                    <!--<el-form-item label="赠品">-->
                    <!--    <el-switch v-model="tableData.isGift" active-text="是" inactive-text="否" active-color="#13ce66"></el-switch>-->
                    <!--</el-form-item>-->
                    <el-form-item label="价格">
                       <span class="goodsTotal">{{tableData.goodsTotal}}</span>  元
                    </el-form-item>
                    <el-form-item>
                        <el-table
                                :data="tableData.row"
                                style="width: 100%">
                            <el-table-column label="数量" width="150">
                                <template slot-scope="scope">
                                    <el-input-number @change="goodsTotal" v-model="scope.row.num" size="small" :min="0"
                                                     :disabled="scope.row.count === 0 || scope.row.goodsPrice === 0" :max="scope.row.count"
                                    ></el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column label="单位" width="60">
                                <template slot-scope="scope">
                                    <el-tag type="warning">{{scope.row.unit}}</el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column label="库存" width="50">
                                <template slot-scope="scope">
                                    <span :class="[scope.row.count === 0 ? 'red' : 'green']">{{scope.row.count}}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="价格" width="85">
                                <template slot-scope="scope">
                                    <span :class="[scope.row.goodsPrice === 0 ? 'red' : 'orange']">{{scope.row.goodsPrice}}</span> 元
                                </template>
                            </el-table-column>
                            <el-table-column label="赠送">
                                <template slot-scope="scope">
                                    <el-input-number v-model="scope.row.giftCount" size="small" :min="0" :max="scope.row.count-scope.row.num"
                                                     :disabled="scope.row.count === 0 || scope.row.goodsPrice === 0 || (scope.row.count-scope.row.num)===0"
                                                     @change="addGift(scope.row)"
                                    ></el-input-number>

                                </template>
                            </el-table-column>

                        </el-table>
                    </el-form-item>
                </div>
                <div v-else>
                    暂无数据
                </div>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeNull">取 消</el-button>
                <el-button type="primary" @click="close">添加到订单</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import API from '@/api/api';
export default {
    name: "SelectGoods",
    props: ['orderGoods'],
    components: {

    },
    data() {
        return {
            //
            dialogVisible: true,
            //
            form: {
                goodsCode: '',
                goodsName: ''
            },
            // 单位列表
            unitList: [],
            //
            goodsItem: {},
            //
            tableData:{
                goodsCode: '',
                goodsName: '',
                row: [],
                giftList: [],
                goodsTotal: 0.00,
            } ,
            // 
            loading: false,
            options: []

        }
    },
    mounted() {
        if (this.orderGoods) {
            console.log(this.orderGoods, "~~~~~~~~~~~~~~~~~~这是数据传输的");
            Object.keys(this.orderGoods).forEach(key => this.form[key] = this.orderGoods[key]);
            this.tableData = JSON.parse(JSON.stringify(this.orderGoods));
        }
        this.selectGoodUnit();

    },
    methods: {
        //
        closeNull() {
            this.$emit("close", null);
        },
        //
        close() {
            console.log(this.orderGoods, '============this.orderGoods');
            console.log(this.tableData, '============this.tableData~~~~');

            // 修改拦截
            if (this.orderGoods) {
                let isEdited = false;
                // 商品数量有没有被更改
                this.orderGoods.row.forEach(o => {
                    this.tableData.row.forEach(t => {
                        if (o.unitId === t.unitId && o.num !== t.num) {
                            isEdited = true;
                        }
                    })
                });
                console.log(isEdited, '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@isEdited');
                // 没有更改，直接返回
                if (!isEdited) {
                    this.$emit("close", null);
                    return;
                }
            }
            let selectCount = 0;
            this.tableData.row.forEach(item => selectCount += item.num);
            if (selectCount > 0) {
                // Object.keys(this.form).forEach(key => {this.tableData[key] = this.form[key]});
                this.tableData.goodsCode = this.form.goodsCode;
                this.tableData.goodsName = this.form.goodsName;
                this.$emit("close", this.tableData);
                console.log('数据变化了！！！！！！！！！！！！！！！！！');
            } else {
                this.$emit("close", null);
            }
        },
        // 查询商品单位
        selectGoodUnit() {
            let url = API.unit.selectUnitList;
            this.$get(url, {}).then( res => {
                let data = res.data;
                if (data.success) {
                    this.unitList = data.data.list;
                }
            }).catch( err => {
                this.$message.error("请求失败!");
            })
        },
        // 商品详情查询
        getGoodsDetail(param) {
            let url = API.goods.goodsQuery;
            this.$get(url, param).then(res => {
                let data = res.data;
                if (data.success && data.data) {
                    this.goodsItem = data.data;
                    // this.goodsItem.status = this.goodsItem.status === '1'? '可用':'不可用';
                    this.form = JSON.parse(JSON.stringify(this.goodsItem));
                    // 清空上一次查询的数据
                    this.tableData.row = [];
                    // 处理渲染到列表的数据
                    this.unitList.forEach(item => {
                        let temp = {
                            goodsCode: data.data.goodsCode,
                            goodsName: data.data.goodsName,
                            unitId: item.unitId,
                            unit: item.unit,
                            discount: 1.0,
                            num: 0,
                            goodsPrice: 0,
                            giftCount: 0,
                            count: 0,
                        };
                        data.data.goodsPriceList.filter(gp => gp.unitId===item.unitId).map(gpItem => {
                            temp.goodsPrice = gpItem.price;
                        });
                        if (data.data.stockList && data.data.stockList.length>0)　{
                            data.data.stockList.filter(s => s.unitId===item.unitId).map(s => {
                                temp.count = s.count? s.count:0;
                            });
                        }

                        this.tableData.row.push(temp);
                    })

                } else if (!data.success){
                    this.$message.closeAll();
                    this.$message.error(data.msg);
                }
            }).catch(err => {
                this.$message.error("请求错误!!")
            })
        },
        // 添加赠品
        addGift(row) {
            let temp = {
                goodsCode: this.form.goodsCode,
            };
            temp.unit = row.unit;
            temp.count = row.giftCount;
            this.tableData.giftList.push(temp);
        },
        //
        getGoodsDetailByGoodsCode() {
            let param = {
                goodsCode: JSON.parse(JSON.stringify(this.form.goodsCode)),
            };
            this.getGoodsDetail(param);
        },
        //
        getGoodsDetailByGoodsName() {
            let param = {
                goodsName: JSON.parse(JSON.stringify(this.form.goodsName)),
            };
            this.getGoodsDetail(param);
        },
        // 计算当前商品的价格
        goodsTotal() {
            this.tableData.goodsTotal = 0.00;
            this.tableData.row.forEach(item => {
                this.tableData.goodsTotal += (item.num * item.goodsPrice);
            })
        },
        //
        getGoodsList(goodsName) {
            let query = {
                param: {
                    goodsName,
                }
            };
            this.$post(API.goods.selectList, query).then( res => {
                let data = res.data;
                if (data.success) {
                    data.data.list?.map(item => {
                        item.label = item.goodsName;
                    })
                    this.options = data.data.list;
                }
            })
            console.log("++++++++  this.options", this.options);
        }
    },
}
</script>

<style lang="scss" scoped>
    .header-row{
        height: 20px;
        text-align: center;
    }
    .red{
        color: red;
        font-weight: bolder;
        font-size: 17px;
    }
    .green {
        color: mediumseagreen;
    }
    .orange {
        color: orange;
    }
    .goodsTotal{
        color: #eecf11;
        font-weight: bolder;
        font-size: 20px;
    }
</style>
